package com.echo.im.client.handler.factory;

import com.echo.im.client.handler.MessageHandler;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author lxy
 * @date 2024-08-14
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class DefaultMessageHandlerFactory implements MessageHandlerFactory {

    private final Map<Class, MessageHandler> handlers=new HashMap<>();
    private final List<MessageHandler> messageHandlerList;

    @PostConstruct
    public void init() {
        for (MessageHandler messageHandler : messageHandlerList) {
            Class messageType = extractMessageType(messageHandler);
            if (messageType != null) {
                handlers.put(messageType, messageHandler);
            } else {
                log.warn("Cannot determine the generic type of the message handler: {}", messageHandler.getClass());
            }
        }
    }

    @Override
    public MessageHandler<?> getHandler(Class<?> messageType) {
        return handlers.get(messageType);
    }

    private <T> Class<T> extractMessageType(MessageHandler<T> handler) {
        // 获取 handler 实例的类
        Type[] interfaces = handler.getClass().getGenericInterfaces();

        // 遍历所有接口，找到 MessageHandler
        for (Type type : interfaces) {
            if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;

                // 确保是 MessageHandler 接口
                if (parameterizedType.getRawType() == MessageHandler.class) {
                    // 获取泛型参数的实际类型
                    Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0];
                    if (actualTypeArgument instanceof Class<?>) {
                        return (Class<T>) actualTypeArgument;
                    }
                }
            }
        }

        // 如果没有找到合适的泛型参数类型，抛出异常或返回 null
        throw new IllegalStateException("Cannot extract message type from handle");
    }




}
